package cn.fz.difydemo01.service;

import cn.fz.difydemo01.domain.dto.DifyChatMessagesRequest;
import cn.fz.difydemo01.domain.enums.ResponseModeEnum;
import cn.fz.difydemo01.domain.vo.StreamResponse;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.HashMap;

@Slf4j
@Service
public class DifyService {

    @Value("${dify.url.chat}")
    private String chatUrl;

    @Value("${dify.api-key}")
    private String apiKey;

    // 发送对话消息
    public Flux<StreamResponse> streamingMessage(String query, String conversationId, String userName){
        DifyChatMessagesRequest body = getBody(query, conversationId, userName);

        //2.使用webclient发送post请求
        return WebClient.create().post()
                .uri(chatUrl)
                .headers(httpHeaders -> {
                    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                    httpHeaders.setBearerAuth(apiKey);
                })
                .bodyValue(JSON.toJSONString(body))
                .retrieve()
                .bodyToFlux(StreamResponse.class);
                // .filter(this::shouldInclude)
                // .onErrorResume(ee -> System.out.println(ee.getMessage()));
    }

    private boolean shouldInclude(StreamResponse streamResponse) {
        // 示例：只要message节点的数据和message_end节点的数据
        if (streamResponse.getEvent().equals("message")
                || streamResponse.getEvent().equals("message_end")) {
            return true;
        }
        return false;
    }

    private DifyChatMessagesRequest getBody(String query, String conversationId, String userName){
        //1.设置请求体
       return DifyChatMessagesRequest.builder()
                .inputs(new HashMap<>())
                .query(query)
                .responseMode(ResponseModeEnum.STREAM.getValue())
                .conversationId(null==conversationId?"":conversationId)
                .user(userName)
                .build();
        //如果存在自定义入参可以加到如下Map中
        //Map<String, Object> commoninputs = new HashMap<>();
        //commoninputs.put("search_type", searchType);
        //body.setInputs(commoninputs);
    }

    public Flux<String> streamingMessage2(String query, String conversationId, String userName) {
        DifyChatMessagesRequest body = getBody(query, conversationId, userName);

        //2.使用webclient发送post请求
        return WebClient.create().post()
                .uri(chatUrl)
                .headers(httpHeaders -> {
                    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                    httpHeaders.setBearerAuth(apiKey);
                })
                .bodyValue(JSON.toJSONString(body))
                .retrieve()
                .bodyToFlux(String.class);
                // .retrieve()
                // .bodyToFlux(StreamResponse.class);
    }
}
